import 'dart:async';
import 'dart:convert';

import 'package:e_reception_flutter/common_widgets/common_bubble_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_detail_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail_search/company_detail_search_page.dart';
import 'package:e_reception_flutter/ui/index/bean/index_top_base_info.dart';
import 'package:e_reception_flutter/ui/index/bean/index_top_info_response_bean.dart';
import 'package:e_reception_flutter/ui/index/even/location_changed_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/terminal_scan_page.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../index_view_model.dart';

/// 首页-顶部公司名和公司logo
///
/// @author: zengxiangxi
/// @createTime: 1/5/21 4:29 PM
/// @specialDemand:
class IndexTopCompanyAndLogoWidget extends StatefulWidget {
  final UserDataBean user;
  // final IndexTopInfoDataBean topInfo;
  final IndexTopBaseInfo baseInfo;
  final bool isShowTips;

  final VoidCallback onTapTips;

  final String defaultgps;

  final VoidCallback onScanResult;

  // static const String SP_TIPS_KEY = "SP_isThereUserTips";
  IndexTopCompanyAndLogoWidget({Key key, this.user,  this.isShowTips, this.onTapTips,
    this.baseInfo, this.defaultgps, this.onScanResult})
      : super(key: key);

  @override
  _IndexTopCompanyAndLogoWidgetState createState() => _IndexTopCompanyAndLogoWidgetState();
}

class _IndexTopCompanyAndLogoWidgetState extends BaseState<IndexTopCompanyAndLogoWidget> {
  int tips = 0;
  // IndexViewModel _viewModel;
  // StreamSubscription _attendanceStreamSubscription;
  // IndexTopBaseInfo baseInfo;
  // @override
  // void initState() {
  //   super.initState();
  // baseInfo = IndexTopBaseInfo();
  // _viewModel = IndexViewModel(this);
  // _viewModel?.indexTopBaseValueNotifier?.addListener(() {
  //   baseInfo = _viewModel?.indexTopBaseValueNotifier?.value;
  //   String topCacheKey = "app/appHomeBaseInfo"+ UserRepository.getInstance().authId ?? ""
  //       + UserRepository.getInstance().companyId ?? "";
  //   SharePreferenceUtil.putString(topCacheKey, json.encode(baseInfo));
  //   setState(() { });
  // });
  // _viewModel?.getHomeBaseInfo();
  // _attendanceStreamSubscription = VgEventBus.global.on<ArtificialAttendanceUpdateEvent>().listen((event) {
  //   _viewModel?.getHomeBaseInfo();
  //   setState(() { });
  // });
  // }

  // @override
  // void dispose() {
  //   _attendanceStreamSubscription.cancel();
  //   super.dispose();
  // }
  bool _hideBubble = false;

  @override
  Widget build(BuildContext context) {
    showUploadFaceDialog(true);
    // bool isThereUser = false;//点击隐藏弹窗
    // int bindTerminalListNum = widget.topInfo?.bindTerminalList?.length ?? 0;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        widget.onTapTips?.call();
        CompanyDetailPage.navigatorPush(context,widget?.defaultgps);
        if(_showFaceDialog()){
          showUploadFaceDialog(false);
        }

      },
      child: Container(
        margin: const EdgeInsets.only(top: 18, bottom: 0),
        height: _isCompanyname() ? 70 :50,
        child: _toRowMainWidget(context),
      ),
    );
  }

  Widget _toRowMainWidget(context) {
    return Stack(
      overflow: Overflow.visible,
      children: <Widget>[
        Container(
          padding: const EdgeInsets.only(left: 20),
          child: Row(
            children: <Widget>[
              _toCompanyNameAndPersonWidget(context),
              Spacer(),
              _toCompanyLogoWidget(),
            ],
          ),
        ),
        //当终端大于等于1且无用户时提示  false 没有用户   true有用户  bindTerminalListNum>=1 &&
        if((widget?.baseInfo?.data?.comPersonCnt??0) == 1)
          _toBubbleDialog(),
        if(_showFaceDialog())
          _toBubbleFaceRecognitionDialog()

      ],
    );
  }

  bool _showFaceDialog(){
    if(AppOverallDistinguish.enableFaceRecognition()&&(widget?.baseInfo?.data?.comPersonCnt??0) >1 && (widget?.baseInfo?.data?.noFaceCnt ?? 0)>=1){
      return true;
    }else{
      return false;
    }
  }

  Widget _toBubbleFaceRecognitionDialog(){
    //启用人脸识别 00启用 01关闭
    if((tips??0)>=3 || _hideBubble){
    // if(_hideBubble){
      return Container();
    }
    return Positioned(
      right: 15,
      child: Container(
        height: 52,
        width: 102,
        child: Bubble(
          direction: BubbleDirection.left,
          color: ThemeRepository.getInstance().getMinorYellowColor_FFB714(),
          child: Stack(
            children: [
              Center(
                child: Padding(
                  padding: const EdgeInsets.only(left: 0,right: 0,top: 0, bottom: 0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        "共${widget?.baseInfo?.data?.noFaceCnt ?? 0}名用户",
                        maxLines: 1,
                        style: TextStyle(color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(), fontSize: 13,), textAlign: TextAlign.center,
                      ),
                      Text(
                        "需上传人脸",
                        style: TextStyle(color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(), fontSize: 13,), textAlign: TextAlign.center,
                      ),
                    ],
                  ),
                ),
              ),
              Positioned(
                right: 0,
                top: 0,
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: (){
                    setState(() {
                      _hideBubble = true;
                    });
                  },
                  child: Container(
                    width: 30,
                    height: 30,
                    alignment: Alignment.topRight,
                    child: Image.asset(
                      "images/icon_close_volume_dialog.png",
                      width: 7,
                      height: 7,
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Future<int> showUploadFaceDialog(bool ontap) async {
    String key = "key_show_face_dialog_flg"+UserRepository.getInstance().getPhone();
    int value = await SharePreferenceUtil.getInt(key);
    if(ontap){//加载
      tips = value;
    }else{
      int phones = value??0;
      if(phones==0){
        SharePreferenceUtil.putInt(key, 1);
      }else if(phones==1){
        SharePreferenceUtil.putInt(key, 2);
      }else if(phones==2){
        SharePreferenceUtil.putInt(key, 3);
      }
    }
  }


  Widget _toCompanyLogoWidget() {
    return Container(
      height: 50,
    );
    return Builder(
      builder: (BuildContext context) => GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          VgToastUtils.toast(context, "更换logo～");
        },
        child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Container(
              width: 50,
              height: 50,
              child: VgCacheNetWorkImage(
                widget?.baseInfo?.data?.companyInfo?.companylogo ?? "",
                placeWidget: _toPlaceAndErrorWidget(),
                errorWidget: _toPlaceAndErrorWidget(),
                imageQualityType: ImageQualityType.middleUp,
              ),
            )
        ),
      ),
    );
  }

  Widget _toPlaceAndErrorWidget(){
    return Image.asset(
      "images/index_company_logo_ico.png",
      fit: BoxFit.cover,
    );
  }

  Widget _toCompanyNameAndPersonWidget(context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        _toCompanyNameAndGoWidget(context),
        if(_isCompanyname())
          _showFullNameEnterprise(),
        _toRowPersonNameWidget(),
      ],
    );
  }

  bool _isCompanyname(){
    if(widget.user?.companyInfo?.companyname!="" && widget.user?.companyInfo?.companyname!=null){
      if(widget.user?.companyInfo?.companyname == widget.user?.companyInfo?.companynick){
        return false;
      }
      return true;
    }else{
      return false;
    }
  }

  Widget _showFullNameEnterprise(){
    return Row(
      children: [
        Image.asset(
          "images/full_name.png",
          width: 11.2,
          color: Color(0xFF4496F7),
        ),
        SizedBox(
          width: 5,
        ),
        Container(
          width: 260,
          child: Text(
            "${widget.user?.companyInfo?.companyname ?? ""}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: Color(0xFFBFC2CC), fontSize: 13, height: 1.2),
          ),
        ),
      ],
    );
  }

  Widget _toBubbleDialog(){
    if(widget?.user?.comUser?.putpicurl!=null&&widget?.user?.comUser?.putpicurl!=""){
      return Container();
    }
    bool showFace = UserRepository.getInstance().userData.companyInfo.isShowFaceRecognition();
    if(!(showFace??false)){
      return Container();
    }
    // bool isThereUser = topInfo?.PVCnt?.isThereUser ?? false;

    return Positioned(
      right: 15,
      child: Container(
        height: 52,
        width: 102,
        child: Bubble(
          padding: const EdgeInsets.only(left: 8,right: 8,top: 6,bottom: 6),
          direction: BubbleDirection.left,
          color: Colors.blue,
          child: Center(
            child: Text(
              "添加用户人脸  启用刷脸功能",
              style: TextStyle(color: Color(0xFFFFFFFF), fontSize: 13,), textAlign: TextAlign.center,
            ),
          ),
        ),
      ),
    );
  }

  ///企业名+箭头
  Widget _toCompanyNameAndGoWidget(context) {
    return Container(
      width: ScreenUtils.screenW(context) - 20,
      child: Row(
        children: <Widget>[
          Expanded(
            child: Row(
              children: [
                ConstrainedBox(
                  constraints: BoxConstraints(
                    maxWidth: ScreenUtils.screenW(context) - 151,
                  ),
                  child: Text(VgStringUtils.subStringAndAppendSymbol(
                      widget?.baseInfo?.data?.companyInfo?.companynick, 12,
                      symbol: "...") ?? "(公司名称)",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 24,
                        height: 1.2,
                        fontWeight: FontWeight.w600),
                  ),
                ),
                SizedBox(
                  width: 6.5,
                ),
                Image.asset(
                  "images/index_arrow_ico.png",
                  width: 8,
                  color: Colors.white,
                ),
                SizedBox(
                  width: 6.5,
                ),
              ],
            ),
          ),

          Visibility(
            visible: (widget?.baseInfo?.data?.comPersonCnt??0) > 1,
            // visible: false,
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                //主页面搜索按钮
                CompanyDetailSearchPage.navigatorPush(context);
              },
              child: Container(
                  height: 28,
                  width: 45,
                  padding: const EdgeInsets.only(left: 15, right: 10),
                  child: Center(
                    child: Image.asset(
                      "images/common_search_ico.png",
                      color: Colors.white,
                      width: 20,
                    ),
                  )),
            ),
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () async{
              bool result = await TerminalScanPage.navigatorPush(context, widget?.defaultgps, AppMain.ROUTER);
              if(result != null){
                widget?.onScanResult?.call();
              }
            },
            child: Container(
                width: 50,
                height: 28,
                padding: const EdgeInsets.only(left: 15, right: 15),
                child: Center(
                  child: Image.asset(
                    "images/icon_scan_code.png",
                    color: Colors.white,
                    width: 20,
                  ),
                )),
          ),

        ],
      ),
    );
  }

  ///人名
  Widget _toRowPersonNameWidget() {

    final bool isSuperAdmin = VgRoleUtils.isSuperAdmin(widget?.baseInfo?.data?.roleid);
    return Row(
      children: <Widget>[
        Image.asset(
          "images/index_person_label_ico.png",
          width: 12,
          color: isSuperAdmin ? null: Color(0xFF4496F7),
        ),
        SizedBox(
          width: 5,
        ),
        CommonConstraintMaxWidthWidget(
          maxWidth: (VgToolUtils.getScreenWidth() /3)*2,
          child: Text(
            "${VgStringUtils.subStringAndAppendSymbol(
                widget.user?.comUser?.name, 7,
                symbol: "...") ?? "-"}"
                "/"
                "${isSuperAdmin ?"超级管理员" :"普通管理员"}"
                "/"
                "管理${widget?.baseInfo?.data?.manageCnt ?? 0}人",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(color: Color(0xFFBFC2CC), fontSize: 13, height: 1.2),
          ),
        ),
        // Container(
        //   width: 0.5,
        //   height: 13,
        //   margin: const EdgeInsets.symmetric(horizontal: 10),
        //   color: VgColors.INPUT_BG_COLOR,
        // ),
        // Text(
        //   "管理${topInfo?.manageCnt ?? 0}人",
        //   maxLines: 1,
        //   overflow: TextOverflow.ellipsis,
        //   style: TextStyle(color: Color(0xFFBFC2CC), fontSize: 13, height: 1.2),
        // ),
      ],
    );
  }
}
